package com.hzsparrow.ai.controller;

import com.hzsparrow.ai.entity.User;
import com.hzsparrow.ai.security.JwtUtils;
import com.hzsparrow.ai.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 认证控制器
 */
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ResponseEntity<?> authenticateUser(@RequestBody LoginRequest loginRequest) {
        try {
            logger.info("尝试登录用户: {}", loginRequest.getUsername());
            
            // 检查用户是否存在
            User existingUser = userService.getUserByUsername(loginRequest.getUsername());
            if (existingUser == null) {
                logger.warn("登录失败: 用户 {} 不存在", loginRequest.getUsername());
                return ResponseEntity.badRequest().body("Error: 用户名不存在");
            }
            
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(
                            loginRequest.getUsername(),
                            loginRequest.getPassword()));

            SecurityContextHolder.getContext().setAuthentication(authentication);
            String jwt = jwtUtils.generateJwtToken(authentication);

            User user = userService.getUserByUsername(loginRequest.getUsername());
            logger.info("用户 {} 登录成功", user.getUsername());
            
            Map<String, Object> response = new HashMap<>();
            response.put("token", jwt);
            response.put("type", "Bearer");
            response.put("id", user.getId());
            response.put("username", user.getUsername());
            response.put("email", user.getEmail());
            response.put("role", user.getRole());

            return ResponseEntity.ok(response);
        } catch (AuthenticationException e) {
            logger.error("用户 {} 登录失败: {}", loginRequest.getUsername(), e.getMessage());
            return ResponseEntity.badRequest().body("Error: 用户名或密码错误");
        } catch (Exception e) {
            logger.error("登录过程发生异常: {}", e.getMessage(), e);
            return ResponseEntity.badRequest().body("Error: 登录处理过程发生错误");
        }
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public ResponseEntity<?> registerUser(@RequestBody User user) {
        try {
            logger.info("尝试注册新用户: {}", user.getUsername());
            
            // 检查用户名是否已存在
            if (userService.getUserByUsername(user.getUsername()) != null) {
                logger.warn("注册失败: 用户名 {} 已被占用", user.getUsername());
                Map<String, String> response = new HashMap<>();
                response.put("message", "用户名已被占用");
                return ResponseEntity.badRequest().body(response);
            }

            // 检查邮箱是否已存在
            User existingUser = userService.getOne(
                    new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<User>()
                            .eq(User::getEmail, user.getEmail())
            );
            if (existingUser != null) {
                logger.warn("注册失败: 邮箱 {} 已被注册", user.getEmail());
                Map<String, String> response = new HashMap<>();
                response.put("message", "邮箱已被注册");
                return ResponseEntity.badRequest().body(response);
            }

            // 创建用户
            userService.createUser(user);
            logger.info("用户 {} 注册成功", user.getUsername());

            Map<String, String> response = new HashMap<>();
            response.put("message", "用户注册成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("注册过程发生异常: {}", e.getMessage(), e);
            Map<String, String> response = new HashMap<>();
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 初始化管理员账户（用于测试）
     */
    @GetMapping("/init-admin")
    public ResponseEntity<?> initAdminUser() {
        try {
            // 检查是否已存在admin用户
            User existingAdmin = userService.getUserByUsername("admin");
            if (existingAdmin != null) {
                return ResponseEntity.ok("管理员账户已存在");
            }
            
            // 创建管理员用户
            User adminUser = new User();
            adminUser.setUsername("admin");
            adminUser.setPassword("admin");
            adminUser.setNickname("管理员");
            adminUser.setEmail("admin@example.com");
            adminUser.setRole("ROLE_ADMIN");
            adminUser.setEnabled(true);
            
            userService.createUser(adminUser);
            
            return ResponseEntity.ok("管理员账户创建成功");
        } catch (Exception e) {
            logger.error("创建管理员账户失败: {}", e.getMessage(), e);
            return ResponseEntity.badRequest().body("创建管理员账户失败: " + e.getMessage());
        }
    }

    /**
     * 登录请求类
     */
    public static class LoginRequest {
        private String username;
        private String password;

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }
    }
} 